package org.gjw.security.filter;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import org.gjw.bean.SysUser;
import org.gjw.security.SecurityConfig;
import org.gjw.security.component.AuthUserDetails;
import org.gjw.service.SysUserService;
import org.gjw.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author guojunwang
 * @date 2021-06-26 12:06
 */
@Component
public class JwtTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private SysUserService sysUserService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String token = StrUtil.blankToDefault( request.getHeader("token"),request.getParameter("token") );

        //如果token不为空
        if( StrUtil.isNotBlank( token ) && SecurityContextHolder.getContext().getAuthentication() == null ){
            String username = jwtUtil.getUserNameFromToken(token);
            SysUser sysUser = sysUserService.getBaseMapper().getUserByUsername(username);

            if( jwtUtil.validateToken(token,sysUser) ){
                AuthUserDetails authUserDetails = BeanUtil.copyProperties(sysUser, AuthUserDetails.class);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(token,null,authUserDetails.getAuthorities() );
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(request,response);
    }
}
